/* eslint-disable @typescript-eslint/no-unused-vars */
import { useExternal } from 'ahooks';
import { App } from 'antd';
import React, { useEffect, useRef } from 'react';
import { YmVideoPlayerProps } from './interface';

/**
 * @desc 根据vid获取视频接口
 */
function getVePlayerVidTokenFromYm({ vid }: { vid: string }) {
  return new Promise<string>((resolve, reject) => {
    if (vid) {
      const xhr = new XMLHttpRequest();
      const sp = new URLSearchParams({ vid });
      const url = new window.URL(
        '/message/huoshan/video/getPlayAuthToken?' + sp.toString(),
        window.location.origin,
      );
      xhr.open('get', url);

      xhr.onloadend = () => {
        try {
          const data = JSON.parse(xhr.response);
          console.log(data);
          resolve(data.data);
        } catch (e) {
          reject('请求失败');
        }
      };

      xhr.send();
    } else {
      reject('请传入正确的vid');
    }
  });
}

const YmVideoPlayer: React.FC<YmVideoPlayerProps> = (props) => {
  const jsStatus = useExternal(
    'https://unpkg.byted-static.com/volcengine/veplayer/1.5.2/dist/index.min.js',
    { type: 'js', keepWhenUnused: true },
  );
  const cssStatus = useExternal(
    'https://unpkg.byted-static.com/volcengine/veplayer/1.5.2/dist/index.min.css',
    { type: 'css', keepWhenUnused: true },
  );

  const { message } = App.useApp();
  const {
    vid,
    id,
    width,
    height,
    url,
    postUrl,
    onInitialPlayerInstance,
    getPlayerAuthTokenApi = getVePlayerVidTokenFromYm,
  } = props;
  const videoPlayerRef = useRef<HTMLDivElement>(null);
  //@ts-ignore
  // eslint-disable-next-line react-hooks/rules-of-hooks

  // // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (jsStatus !== 'ready') {
      return;
    }
    console.log('--getPlayerAuthTokenApi--:', getPlayerAuthTokenApi);
    //实例化播放器
    let playerConfig: YmVideoPlayerProps = {
      root: videoPlayerRef.current,
      width,
      height,
    };

    new Promise((resolve, reject) => {
      if (url) {
        resolve(new window.VePlayer({ ...playerConfig, url }));
      } else if (vid && typeof getPlayerAuthTokenApi === 'function') {
        getPlayerAuthTokenApi({ vid }).then((playAuthToken) => {
          console.log(playAuthToken);
          resolve(
            new window.VePlayer({
              ...playerConfig,
              getVideoByToken: {
                playAuthToken,
              },
              // 重播的方法
              onTokenExpired: async () => {
                const playAuthToken = await getPlayerAuthTokenApi({ vid });
                return { playAuthToken };
              },
            }),
          );
        });
      } else {
        message.error('缺少参数vid/url');
        reject();
      }
    }).then(
      (tempPlayerSdk) => {
        onInitialPlayerInstance?.(tempPlayerSdk);
      },
      () => {},
    );

    return () => {
      if (videoPlayerRef.current) {
        // 注：<Drawer destroyOnClose={false} /> 时， Drawer- div:ym_video_player dom没有被销毁, 每次打开Drawer时，div:ym_video_player.appendChild(new window.VePlayer())
        videoPlayerRef.current.innerHTML = '';
      }
    };
  }, [url, vid, jsStatus, cssStatus]);

  return <div id={id} ref={videoPlayerRef}></div>;
};

export default YmVideoPlayer;
